package com.geeguo.ebuilder.client.runner;

import com.geeguo.ebuilder.core.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Slf4j
public class ApplicationStartupListener implements ApplicationRunner {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 系统启动信息
     */
    public static final String APPLICATION_STARTUP_INFO = "\n" +
            "==================================================\n" +
            "Application Name:{}\n" +
            "PID:{}\n" +
            "URL:{}\n" +
            "Startup Time:{}\n" +
            "==================================================";

    @Override
    public void run(ApplicationArguments args) {
        String applicationName = applicationContext.getEnvironment().getProperty("spring.application.name");
        String applicationJvmName = ManagementFactory.getRuntimeMXBean().getName();
        String applicationStartupTime = DateUtils.dateTimeFormat(new Date(applicationContext.getStartupDate()));
        log.info(APPLICATION_STARTUP_INFO,
                applicationName,
                applicationJvmName.split("@")[0],
                this.getUrl(),
                applicationStartupTime);
    }

    public String getUrl() {
        return "http://" + getHost() + ":" + getPort() + getContextPath();
    }

    public String getHost() {
        String host = "0.0.0.0";
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.error("Failed to get local host address", e);
        }
        if (address != null) {
            host = address.getHostAddress();
        }
        return host;
    }

    public String getPort() {
        return applicationContext.getEnvironment().getProperty("server.port");
    }

    public String getContextPath() {
        String contextPath = applicationContext.getEnvironment().getProperty("server.servlet.context-path");
        if (contextPath == null) {
            contextPath = "";
        }
        return contextPath;
    }
}
